//
//  WBStatusViewModel.swift
//  SinaWeibo
//
//  Created by 风不会停息 on 2016/11/18.
//  Copyright © 2016年 风不会停息. All rights reserved.
//微博cell的视图模型，用来处理微博cell显示的数据

import UIKit

class WBStatusViewModel: NSObject {
    
    
    var iconURL: URL?
    var status:WBStatus?{
        didSet{
           iconURL = URL(string: status?.user?.avatar_large ?? "")
            self.dealmRankView()
            self.dealavatarView()
//            self.timeText = dealWeiboDate(str: status?.created_at ?? "")
            self.sourceText = dealWeiboSource(source: status?.source ?? "")
            self.originalAttributedString = self.dealWeiboText(str: status?.text ?? "")
            
            self.retweetedAttributedString =  self.dealWeiboText(str: status?.retweeted_status?.text ?? "")
        }
    }
    var avatarView:UIImage?
    
    var sourceText: String?
    
    
    //原创微博的属性字符串
    var originalAttributedString: NSMutableAttributedString?
    
    //转发微博的属性字符串
    var retweetedAttributedString: NSMutableAttributedString?
    
    var timeText: String? {
        //1.实例化日期格式化对象
        let dateFormater = DateFormatter()
        //2.指定格式化符
        dateFormater.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
        //在真机上必须设置本地化信息否则转换失败
        dateFormater.locale = Locale(identifier: "en")
        //3.将字符串转换日期对象
        guard let sinaDate = dateFormater.date(from: status?.created_at ?? "") else {
            return "穿越时空的少年"
        }
//        print(sinaDate)
        //4.处理日期
        //4.1 判断是否是今年 Calendar 提供非常丰富的日期处理函数
        let calender = Calendar.current
        let currentDate = Date()
        let result = calender.dateComponents([.day,.year], from: sinaDate, to: currentDate)
        if result.year == 0 {
            //今年
            if calender.isDateInToday(sinaDate) {
                //今天
                //获取当前时间和sinaDate秒的差值
                let delta = currentDate.timeIntervalSince(sinaDate)
                if delta < 60 {
                    //刚刚
                    return "刚刚"
                } else if delta < 3600 {
                    return "\(Int(delta / 60))分钟前"
                } else {
                    return "\(Int(delta / 3600))小时前"
                }
            } else if calender.isDateInYesterday(sinaDate) {
                //昨天 昨天 HH:mm
                dateFormater.dateFormat = "昨天 HH:mm"
                return dateFormater.string(from: sinaDate)
            } else {
                //其他 MM-dd HH:mm
                dateFormater.dateFormat = "MM-dd HH:mm"
                return dateFormater.string(from: sinaDate)
            }
        } else {
            //非当年
            dateFormater.dateFormat = "yyyy-MM-dd HH:mm"
            return dateFormater.string(from: sinaDate)
        }
    }

    
    var mRankView:UIImage?
    
    //加入计算型属性，判断应该返回什么类型微博的pic_urls
    var imageUrls:[WBPictureInfo]?{
        if status?.retweeted_status == nil{
            return status?.pic_urls
        }
        return status?.retweeted_status?.pic_urls
    }
    

    //处理微博来源
    private func dealWeiboSource(source: String) -> String {
        //<a href=\"http://app.weibo.com/t/feed/6vtZb0\" rel=\"nofollow\">iPhone 6s 土豪金</a>
        let startFlag = "\">"
        let endFlag = "</a>"
        guard let startRange = source.range(of: startFlag),
            let endRange = source.range(of: endFlag) else {
                return "来自火星"
        }
        
        //upperBound 最大边界 lowerBound: 最小边界
        let range = startRange.upperBound..<endRange.lowerBound
        let subStr = source.substring(with: range)
        return subStr
    }
    
    //计算型属性就不用这个函数了
    private func dealWeiboDate(str: String) -> String {
        
//        let dateString = "Sat Nov 19 10:56:03 +0800 2016"
        //Sat Nov 19 11:28:03 +0800 2016
        //先将字符串处理成日期对象
        //1.实例化日期格式化对象
        let dateFormater = DateFormatter()
        //2.指定格式化符
        dateFormater.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
                //在真机上必须设置本地化信息否则转换失败
        dateFormater.locale = Locale(identifier: "en")
        //3.将字符串转换日期对象
        guard let sinaDate = dateFormater.date(from: str) else {
            return "来自火星"
        }

        //4.处理日期
        //4.1 判断是否是今年 Calendar 提供非常丰富的日期处理函数
        let calender = Calendar.current
        let currentDate = Date()
        let result = calender.dateComponents([.day,.year], from: sinaDate, to: currentDate)
        if result.year == 0 {
            //今年
            if calender.isDateInToday(sinaDate) {
                //今天
                //获取当前时间和sinaDate秒的差值
                let delta = currentDate.timeIntervalSince(sinaDate)
                if delta < 60 {
                    //刚刚
                    return "刚刚"
                } else if delta < 3600 {
                    return "\(Int(delta / 60))分钟前"
                } else {
                    return "\(Int(delta / 3600))小时前"
                }
            } else if calender.isDateInYesterday(sinaDate) {
                //昨天 昨天 HH:mm
                dateFormater.dateFormat = "昨天 HH:mm"
                return dateFormater.string(from: sinaDate)
            } else {
                //其他 MM-dd HH:mm
                dateFormater.dateFormat = "MM-dd HH:mm"
                return dateFormater.string(from: sinaDate)
            }
        } else {
            //非当年
            dateFormater.dateFormat = "yyyy-MM-dd HH:mm"
            return dateFormater.string(from: sinaDate)
        }
    }

    
    
    private func dealavatarView(){
        
       let type = status?.user?.verified_type ?? -1
        switch type {
        case 0:
            avatarView = #imageLiteral(resourceName: "avatar_vip")
        case 2,3,5:
            avatarView = #imageLiteral(resourceName: "avatar_enterprise_vip")
        case 220:
            avatarView = #imageLiteral(resourceName: "avatar_grassroot")
        default:
            //没有认证
            avatarView = nil
        }
        
    }
    //处理用户等级
    private func dealmRankView(){
        
        let mbrank = status?.user?.mbrank ?? 0
        if mbrank > 0 && mbrank < 7 {
            //赋值
            mRankView = UIImage(named: "common_icon_membership_level\(mbrank)")
        }
        
    }
    //将微博正文和转发微博正文处理成富文本
    private func dealWeiboText(str:String) -> NSMutableAttributedString{
        //1.实例化正则表达式对象   设置查找对象
        //正则表达式中中括号表示的是一位需要转义
        let pattern = "\\[.*?\\]"
        
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        //2.通过规则在字符串中查找目标字符串 -->[NSTextCheckResult]
        
        let results = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.characters.count))
        //3.遍历结果集，获取图片表情字符串(倒叙遍历)
        
        let font = UIFont.systemFont(ofSize: 15)
        
        let lineHeight = font.lineHeight
        
        let strM = NSMutableAttributedString(string: str)
        
        for result in results.reversed(){
            
            let range  = result.rangeAt(0)
            
            let sub = (str as NSString).substring(with: range)
           
             //4.根据表情字符串在表情数组中查找对应的表情模型（图片路径）
            
            
            
            if let em = HMEmoticonTools.sharedEmoticonTools.findEmotion(chs: sub){
                 //5、将图片转化为富文本   要使用YYText提供
                let image = UIImage(named: em.imagePath!, in: HMEmoticonTools.sharedEmoticonTools.emoticonBundle, compatibleWith: nil)
                
                let imageTxt = NSMutableAttributedString.yy_attachmentString(withContent: image, contentMode: .scaleAspectFit, attachmentSize: CGSize(width: lineHeight, height: lineHeight), alignTo: font, alignment: .center)
                
               
                  //6.将str转换为可变的富文本
                strM.replaceCharacters(in:  range, with: imageTxt)
                
                
            }

            
        }
        
      //设置富文本字体的大小，并给富文本赋值
        strM.addAttributes([NSFontAttributeName:font], range: NSRange(location: 0, length: strM.length))
        //7、将图片富文本替换到str对应的可变的富文本中
        
        addHighlighted(pattern: "@\\w+", strM: strM)
        addHighlighted(pattern: "#.*?#", strM: strM)
        addHighlighted(pattern: "(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?", strM: strM)
        
        
        
      
        return strM
    }
    
    
    private func addHighlighted(pattern:String,strM:NSMutableAttributedString){
        
        
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        //2.通过规则在字符串中查找目标字符串 -->[NSTextCheckResult]
        
        let str = strM.string
        
        let results = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.characters.count))
        
        
        for result in results{
            let range = result.rangeAt(0)
            
            //let sub = (str as NSString).substring(with: range)
            //给目标字符串添加颜色
            strM.addAttributes([NSForegroundColorAttributeName : UIColor.orange], range: range)
              //给特殊文本添加点击事件
            
            let border = YYTextBorder(fill: UIColor.red, cornerRadius: 3)
            let highted = YYTextHighlight()
            //高亮时文字的颜色
            highted.setColor(UIColor.blue)
            
            highted.setBackgroundBorder(border)
            strM.yy_setTextHighlight(highted, range: range)
            
        }
        
    }

}
